'use strict';
var faye = require('faye');
var lodash = require('lodash');
var express = require('express');
var appApi = require('./app-api');
var confirmOrder = require('./confirm-order');
var table = require('./table');
var inventory = require('./inventory');
var category = require('./category');
var lodash = require('lodash');
var path = require('path');
var rewrite = require('express-urlrewrite');
var {
  scheduleOrderlistNedb
} = require('./../services/schedule');

process.on('uncaughtException', function(err) {
  console.error(err.stack || err);
});
var asyncRouter = require('./async-router');

module.exports = function(app) {

  //cdc路由
  require('./cdc-index')(app);

  //任务调度，一天清楚一次NEDB
  scheduleOrderlistNedb()


  var router = express.Router({
    mergeParams: true
  });

  // app.use('/api/tables/:tableId', router);
  // app.use('/api', router);
  app.use('/api/stores/:storeId', router);

  router = asyncRouter(router);
  app.use('/wexin-orders/assets', express.static(path.join(__dirname,
    '../wexin-orders/assets')));

  router.get('/tables/:tableId/wxinit', function*(req, res, next) {
    // console.log("/tables/:tableId/wxinit", req.params.tableId);
    req.appApi = appApi("wxinit");
    let result = yield req.appApi.get('/tables/' + req.params.tableId +
      '/wxinit');
    res.json(result.data);
  });

  table(app, router);
  inventory(app, router);
  category(app, router);
  confirmOrder(app, router);
  app.param('storeId', function(req, res, next) {
    req.appApi = appApi(req.params.storeId);
    next();
  });

  router.get('/inventories', function*(req, res, next) {
    // console.log("/inventories");
    return (yield req.appApi.get('/inventories')).data;
  });
  router.get('/categories', function*(req, res, next) {
    // console.log("/categories");
    let result = (yield req.appApi.get('/categories'));
    let data = result.data.map(item => lodash.pick(item, ['name', 'id',
      'showOrder'
    ]));
    res.send(data);
  });
  router.get('/tables/:tableId', function*(req, res, next) {
    return (yield req.appApi.get('/tables/' + req.params.tableId)).data;
  });
  router.get('/orders/:tableId', function*(req, res, next) {
    return (yield req.appApi.get('/orders/tables?tableId=' + req.params.tableId))
      .data;
  });

  // router.get('/orders/:tableId', function*(req, res, next) {
  // return (yield req.appApi.get('/orders/tables?tableId=' + req.params.tableId)).data;
  // });
  // app.use(rewrite('/ordering/*', '/wexin-orders/index.html'));

  app.get('/t/jump.html', rewrite('/wexin-orders/jump.html'));
  app.use(rewrite('/t/*', '/wexin-orders/index.html'));



  return Promise.resolve(function(server) {
    var bayeux = new faye.NodeAdapter({
      mount: '/faye',
      timeout: 45
    });
    bayeux.attach(server);
  });
}
